package com.kelaite.procurement.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.service.MessageService;
import com.kelaite.procurement.utils.ApplicationContextUtil;
import com.kelaite.procurement.utils.ConvertUtil;

/**
 * @author think
 *
 */
public class UserLoginInterceptor implements HandlerInterceptor {

	protected static final Logger logger = Logger
			.getLogger(UserLoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object object) throws Exception {
		// 验证用户是否登陆
		Object obj = request.getSession().getAttribute(Constants.CURRENT_USER);
		if (obj == null || !(obj instanceof UserDTO)) {
			response.sendRedirect(request.getContextPath()
					+ "/preLogin.htm?source="
					+ Base64Utils.encodeToString((request.getRequestURI() + (StringUtils
							.isBlank(request.getQueryString()) ? "" : "?"+request
							.getQueryString())).getBytes("UTF-8")));
			return false;
		}
		//获取用户未读消息
		MessageService messageService = (MessageService)ApplicationContextUtil.getBean(request, "messageServiceImpl");
		request.setAttribute("unReadMessage", messageService.getUnReadMessage(ConvertUtil.convertObj(obj, TUser.class)).size());
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object object, Exception exception)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object object, ModelAndView modelAndView) throws Exception {
	}

}
